// File Name: key_logic.c
// Author: kukukukuku~
// Date: 2024-10-24

#include "./Key/inc/key_logic.h"
#include "apm32f00x_gpio.h"
#include "apm32f00x_tmr1.h"
#include "FreeRTOS.h"
#include "task.h"

/**
 * @brief   Key扫描和处理
 * @param   key:    Key对象
 * @retval  None
 * @note    None
*/
void key_scan_and_handle(pKEY_T key)
{
    if(key == NULL || key->handle_func == NULL)
        return;
    
    //检测到按下
    if(key->pressFlag == 0 && GPIO_ReadInputBit(key->gpioPort, key->gpioPin) == key->pressPolarity)
    {
        //延时消抖后还是检测到按下
        vTaskDelay(15);
        if(GPIO_ReadInputBit(key->gpioPort, key->gpioPin) == key->pressPolarity)
        {
            key->pressFlag = 1;
            key->pressCount++;
            key->longPressJudgeCnt = 0;
            key->longPressScanFlag = 1;
            key->state = KEY_STATE_CLICK;
            
            //启动定时器判断是否长按
            if(KEY_TMR->CTRL1_B.CNTEN == BIT_RESET)
                TMR1_Enable(KEY_TMR);
        }
    }
    //检测到松开
    else if(GPIO_ReadInputBit(key->gpioPort, key->gpioPin) != key->pressPolarity)
    {
        key->pressFlag = 0;
        key->longPressScanFlag = 0;
        key->longPressJudgeCnt = 0;
        
        if(key->state != KEY_STATE_RELEASE)
        {
            //短按松开执行短按处理，长按松开清除长按处理
            key->handle = key->state == KEY_STATE_CLICK ? KEY_HANDLE_CLICK : KEY_HANDLE_NONE;
        }
        
        //关闭定时器
        if(KEY_TMR->CTRL1_B.CNTEN == BIT_SET)
        {
            TMR1_Disable(KEY_TMR);
            TMR1_SetCounter(KEY_TMR, 0);
        }
        
        key->state = KEY_STATE_RELEASE;
    }
    
    //处理
    key->handle_func();
}
